package teleradiologia.repository;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.security.providers.encoding.BaseDigestPasswordEncoder;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;

import teleradiologia.domain.Radlabmanager;
import teleradiologia.utils.HibernateUtil;

public class RadlabmanagerDaoImpl implements RadlabmanagerDao {

	private BaseDigestPasswordEncoder encoder = new Md5PasswordEncoder();

	@Override
	public String create(Radlabmanager radlabmanager) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		radlabmanager.getPerson().setPassword(
				encoder.encodePassword(radlabmanager.getPerson().getPassword(),
						radlabmanager.getPerson().getUsername()));

		String nip = (String) session.save(radlabmanager);

		tx.commit();
		session.close();

		return nip;

	}

	@Override
	public void delete(Radlabmanager radlabmanager) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		session.delete(radlabmanager);

		tx.commit();
		session.close();
	}

	@Override
	public Radlabmanager getByNip(String nip) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Radlabmanager radlabmanager = (Radlabmanager) session.get(
				Radlabmanager.class, nip);

		tx.commit();
		session.close();

		return radlabmanager;
	}

	@Override
	public void update(Radlabmanager radlabmanager) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		radlabmanager.getPerson().setPassword(
				encoder.encodePassword(radlabmanager.getPerson().getPassword(),
						radlabmanager.getPerson().getUsername()));

		session.update(radlabmanager);

		tx.commit();
		session.close();
	}

	@Override
	public Radlabmanager getByIdPerson(long idPerson) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Radlabmanager radlabmanager = (Radlabmanager) session.createQuery(
				"from Radlabmanager radlabmanager "
						+ " where radlabmanager.person.id = :idPerson")
				.setLong("idPerson", idPerson).uniqueResult();

		tx.commit();
		session.close();

		return radlabmanager;
	}

	@Override
	public Radlabmanager getByKrsnumber(String krsnumber) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Radlabmanager radlabmanager = (Radlabmanager) session.createQuery(
				"from Radlabmanager radlabmanager "
						+ " where radlabmanager.radiologylab = :krsnumber")
				.setString("krsnumber", krsnumber).list();

		tx.commit();
		session.close();

		return radlabmanager;
	}
}
